package com.ruoyi.project.module.ljw;

import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.project.domain.HeDepartment;
import com.ruoyi.project.domain.HeEventReport;
import com.ruoyi.project.module.ljw.domain.Department;
import com.ruoyi.project.module.ljw.domain.Reporter;
import com.ruoyi.project.module.ljw.domain.TypeSelect;
import com.ruoyi.project.service.IHeDepartmentService;
import com.ruoyi.project.service.IHeEventReportService;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.system.api.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.time.LocalDate;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static com.ruoyi.common.security.utils.SecurityUtils.getLoginUser;

/**
 * 事件上报信息Controller
 *
 * @author ruoyi
 * @date 2023-09-02
 */
@RestController
@RequestMapping("/ljw/report")
public class LjwHeEventReportController extends BaseController {
    @Autowired
    private IHeEventReportService heEventReportService;

    @Autowired
    private IHeDepartmentService heDepartmentService;

    /**
     * 查询事件上报信息列表
     */
    //@RequiresPermissions("project:report:list")
    @GetMapping("/list")
    public TableDataInfo list(HeEventReport heEventReport) {
        startPage();
        List<HeEventReport> list = heEventReportService.selectHeEventReportList(heEventReport);
        return getDataTable(list);
    }

    // 根据事件类型进行查询
    @GetMapping("/list/type")
    public TableDataInfo listType(HeEventReport heEventReport) {
        // 取出字典长度
        int length = Integer.parseInt(heEventReport.getNote1());
        // 将note1置空
        heEventReport.setNote1("");

        // 新建列表存储查询到的事件类型及其数量
        List<TypeSelect> list = new ArrayList<>();

        // 循环每一个类型进行查库
        for (int i = 1; i <= length; i++) {
            // 设置上报事件类型（注意String和int类型）
            if (i < 10) {
                heEventReport.setReportEventType("0" + i + "");
            } else {
                heEventReport.setReportEventType(i + "");
            }

            // 根据条件（事件类型）进行查询
            List<HeEventReport> heEventReports = heEventReportService.selectHeEventReportList(heEventReport);
            // 如果查到的数据不为空
            if (heEventReports.size() != 0) {
                // 新建一个封装好的，用于存储事件类型及其数量的对象
                TypeSelect typeSelect = new TypeSelect();
                // 装入相关值
                if (i < 10) {
                    typeSelect.setReportEventType("0" + i + "");
                } else {
                    typeSelect.setReportEventType(i + "");
                }
                typeSelect.setReportEventNumber(heEventReports.size());
                // 将对象放入列表中
                list.add(typeSelect);
            }
        }
        // 返回整个列表
        return getDataTable(list);
    }

    // 根据事件类型进行查询（时间范围）
    @GetMapping("/list/type/time")
    public TableDataInfo listTypeByTime(HeEventReport heEventReport) {
        // 取出字典长度
        int length = Integer.parseInt(heEventReport.getNote1());
        // 将note1置空
        heEventReport.setNote1("");

        // 取出开始结束时间
        //Long startTimestamp = Long.valueOf(heEventReport.getNote2());
        //Long endTimestamp = Long.valueOf(heEventReport.getNote3());
        // 将note2和note3置空
        //heEventReport.setNote2("");
        //heEventReport.setNote3("");

       /* Date date= DateUtils.dateTime("yyyy-MM-dd HH:mm:ss",heEventReport.getNote2());
        Date date1= DateUtils.dateTime("YYYY-MM-dd HH:mm:ss",heEventReport.getNote3());
        heEventReport.setNote2(date.getTime());
        heEventReport.setNote3(date1.toString());
        System.out.println(heEventReport.getNote2());

        System.out.println(heEventReport.getNote3());*/
        // 新建列表存储查询到的事件类型及其数量
        List<TypeSelect> list = new ArrayList<>();

        // 循环每一个类型进行查库
        for (int i = 1; i <= length; i++) {
            // 设置上报事件类型（注意String和int类型）
            if (i < 10) {
                heEventReport.setReportEventType("0" + i + "");
            } else {
                heEventReport.setReportEventType(i + "");
            }
            // 根据条件（事件类型）进行查询
            List<HeEventReport> heEventReports = heEventReportService.selectHeEventReportListByTime(heEventReport);


            // 如果查到的数据不为空
            if (heEventReports.size() != 0) {
                // 新建一个封装好的，用于存储事件类型及其数量的对象
                TypeSelect typeSelect = new TypeSelect();
                // 装入相关值
                if (i < 10) {
                    typeSelect.setReportEventType("0" + i + "");
                } else {
                    typeSelect.setReportEventType(i + "");
                }
                typeSelect.setReportEventNumber(heEventReports.size());
                // 将对象放入列表中
                list.add(typeSelect);
            }
        }
        // 返回整个列表
        return getDataTable(list);
    }

    // 根据个人进行查询
    @GetMapping("/list/person")
    public Reporter listPerson(HeEventReport heEventReport) {
        // 获取当前登录用户信息
        LoginUser loginUser = getLoginUser();
        SysUser currentUser = loginUser.getSysUser();
        // 获取用户名
        String userName = currentUser.getNickName();

        // 设置填报人
        heEventReport.setReportFiller(userName);
        // 查询
        List<HeEventReport> list = heEventReportService.selectHeEventReportList(heEventReport);
        return new Reporter(userName, list.size());
    }

    // 根据个人进行查询 近6个月
    @GetMapping("/list/person/month")
    public List<Reporter> listPersonByMonth() {
        // 获取当前登录用户信息
        LoginUser loginUser = getLoginUser();
        SysUser currentUser = loginUser.getSysUser();
        // 获取用户名
        String userName = currentUser.getNickName();

        HeEventReport report = new HeEventReport();
        // 设置填报人
        report.setReportFiller(userName);
        // 要返回的数组
        List<Reporter> list = new ArrayList<>();

        // 当前日期
        LocalDate currentDate = LocalDate.now();
        for (int i = 6; i >= 1; i--) {
            // 需要的日期
            LocalDate needDate = currentDate.minusMonths(i);
            getReporterList(report, list, needDate);
        }

        return list;
    }

    // 根据个人进行查询 按季度查询
    @GetMapping("/list/person/season/{season}")
    public List<Reporter> listPersonBySeason(@PathVariable Integer season) {
        // 获取当前登录用户信息
        LoginUser loginUser = getLoginUser();
        // 获取用户名
        String userName = loginUser.getSysUser().getNickName();

        HeEventReport report = new HeEventReport();
        // 设置填报人
        report.setReportFiller(userName);
        // 要返回的数组
        List<Reporter> list = new ArrayList<>();

        // 当前日期
        LocalDate currentDate = LocalDate.now();
        int year = currentDate.getYear();

        if (currentDate.getMonthValue() < 10 && season == 4) {
            for (int month = (season - 1) * 3 + 1; month <= season * 3; month++) {
                LocalDate startDate = LocalDate.of(year - 1, month, 1);
                getReporterList(report, list, startDate);
            }
        } else {
            for (int month = (season - 1) * 3 + 1; month <= season * 3; month++) {
                LocalDate startDate = LocalDate.of(year, month, 1);
                getReporterList(report, list, startDate);
            }
        }
        return list;
    }

    // 抽象出的方法 按月份查询
    private void getReporterList(HeEventReport report, List<Reporter> list, LocalDate date) {
        String startDateStr = date.toString();
        report.setNote1(startDateStr);
        List<HeEventReport> reportList = heEventReportService.selectHeEventReportListByMonth(report);

        Reporter reporter = new Reporter();
        reporter.setReportFiller(startDateStr.substring(0, 7));
        reporter.setCount(reportList.size());

        list.add(reporter);
    }

    // 根据个人进行查询（时间范围）
    @GetMapping("/list/person/time")
    public Reporter listPersonByTime(HeEventReport heEventReport) {
        // 获取当前登录用户信息
        LoginUser loginUser = getLoginUser();
        SysUser currentUser = loginUser.getSysUser();
        // 获取用户名
        String userName = currentUser.getNickName();

        // 设置填报人
        heEventReport.setReportFiller(userName);
        // 查询
        List<HeEventReport> list = heEventReportService.selectHeEventReportListByTime(heEventReport);
        return new Reporter(userName, list.size());
    }

    // 根据科室进行查询
    @GetMapping("/list/department")
    public TableDataInfo listDepartment() {
        // 新建列表存储查询到的科室类型及其数量
        List<Department> list = new ArrayList<>();
        // 查询科室库，获取所有科室信息
        List<HeDepartment> departmentList = heDepartmentService.selectHeDepartmentList(new HeDepartment());
        // 遍历列表，按科室查询
        for (HeDepartment heDepartment : departmentList) {
            HeEventReport heEventReport = new HeEventReport();
            heEventReport.setReportDepartment(heDepartment.getDepartmentNumber());
            // 查询该科室的所有事件
            List<HeEventReport> reports = heEventReportService.selectHeEventReportList(heEventReport);
            // 如果查到的数据不为空
            if (reports.size() > 0) {
                // 新建一个封装对象
                Department deprtment = new Department();
                deprtment.setDepartmentName(heDepartment.getDepartmentName());
                deprtment.setReportNumber(reports.size());
                // 将对象放入列表
                list.add(deprtment);
            }
        }
        return getDataTable(list);
    }

    // 根据科室进行查询（时间范围）
    @GetMapping("/list/department/time")
    public TableDataInfo listDepartmentByTime(HeEventReport heEventReport) {
        // 新建列表存储查询到的科室类型及其数量
        List<Department> list = new ArrayList<>();
        // 查询科室库，获取所有科室信息
        List<HeDepartment> departmentList = heDepartmentService.selectHeDepartmentList(new HeDepartment());
        // 遍历列表，按科室查询
        for (HeDepartment heDepartment : departmentList) {
            heEventReport.setReportDepartment(heDepartment.getDepartmentNumber());
            // 查询该科室的所有事件
            List<HeEventReport> reports = heEventReportService.selectHeEventReportListByTime(heEventReport);
            // 如果查到的数据不为空
            if (reports.size() > 0) {
                // 新建一个封装对象
                Department deprtment = new Department();
                deprtment.setDepartmentName(heDepartment.getDepartmentName());
                deprtment.setReportNumber(reports.size());
                // 将对象放入列表
                list.add(deprtment);
            }
        }
        return getDataTable(list);
    }

    /**
     * 导出事件上报信息列表
     */
    //@RequiresPermissions("project:report:export")
    @Log(title = "事件上报信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, HeEventReport heEventReport) {
        List<HeEventReport> list = heEventReportService.selectHeEventReportList(heEventReport);
        ExcelUtil<HeEventReport> util = new ExcelUtil<HeEventReport>(HeEventReport.class);
        util.exportExcel(response, list, "事件上报信息数据");
    }

    /**
     * 获取事件上报信息详细信息
     */
    //@RequiresPermissions("project:report:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(heEventReportService.selectHeEventReportById(id));
    }

    /**
     * 新增事件上报信息
     */
    //@RequiresPermissions("project:report:add")
    @Log(title = "事件上报信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody HeEventReport heEventReport) {
        return toAjax(heEventReportService.insertHeEventReport(heEventReport));
    }

    /**
     * 修改事件上报信息
     */
    //@RequiresPermissions("project:report:edit")
    @Log(title = "事件上报信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody HeEventReport heEventReport) {
        return toAjax(heEventReportService.updateHeEventReport(heEventReport));
    }

    /**
     * 删除事件上报信息
     */
    //@RequiresPermissions("project:report:remove")
    @Log(title = "事件上报信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(heEventReportService.deleteHeEventReportByIds(ids));
    }


    public static void main(String[] args) {
        //LocalDate currentDate = LocalDate.now();
        //LocalDate preDate = currentDate.minusMonths(1);
        //String ddd = preDate.toString();
        //Date date = Date.from(preDate.atStartOfDay().toInstant(ZoneOffset.UTC));

        LocalDate ddd = LocalDate.of(2024, 6, 30);
        System.out.println(ddd);
    }
}
